package com.yxy.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yxy.base.BusinessException;
import com.yxy.base.Pagingable;
import com.yxy.dao.PersonMapper;
import com.yxy.dao.TenantExtendMapper;
import com.yxy.dto.PersonDto;
import com.yxy.dto.PersonListDto;
import com.yxy.feign.VO.AdminUserInToken;
import com.yxy.model.Person;
import com.yxy.model.TenantExtend;
import com.yxy.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@Slf4j
@Service
public class PersonService {
  @Value("${centerFileServer}")
  private String centerFileServer;//从配置文件中读取 文件上传下载服务器的地址

  @Resource
  private HttpServletRequest request;

  @Autowired
  private TokenCheckUtil tokenCheckUtil;

  @Resource
  private PersonMapper personMapper;

  @Autowired
  private TenantHelper tenantHelper;

  // 创建 or 修改 白名单, 包括图片
  public Person createOrUpdate(PersonDto inputDto) throws BusinessException {
    //验证参数是否合法,比如身份证号和手机号等等
    validateInputDto(inputDto);

    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    Person db = new Person();
    BeanUtils.copyProperties(inputDto, db);

    if (db.getId() == null) { //新增
      db.setCreateUserId(adminUser.getAdminUser().getId());
      db.setCreateUserName(adminUser.getAdminUser().getUsername());
      personMapper.insertSelective(db);
    } else { //修改
      db.setUpdateDate(new Date());
      db.setUpdateUserId(adminUser.getAdminUser().getId());
      db.setUpdateUserName(adminUser.getAdminUser().getUsername());
      personMapper.updateByPrimaryKeySelective(db);
    }
    return db;
  }

  // 参数校验
  private void validateInputDto(PersonDto inputDto) throws BusinessException {
    if (inputDto.getMobile().length() != 11) {
      throw new BusinessException(501, "手机号长度不正确");
    }
    if (inputDto.getIdCardNo().length() != 18) {
      throw new BusinessException(501, "身份证长度不正确");
    }
  }

  public List<Person> getList(PersonListDto query) throws BusinessException{
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();

    Set<Long> tenantIdList = tenantHelper.getTenantIdListFromFront(query.getTenantId());
    query.setTenantIdList(tenantIdList);
    // end
    PageHelper.startPage(query.getPageNumber(), query.getPageSize());
    PageHelper.orderBy("t1.create_date desc");//排序
    List<Person> dbResult = personMapper.selectList(query);
    return dbResult;
  }

  @Transactional(rollbackFor = Exception.class)
  public void deletePerson(long id) throws BusinessException {
    Person person = personMapper.selectByPrimaryKey(id);
    if (person == null) {
      throw new BusinessException(501, "查无此人");
    }

    this.deleteFile(person.getImgUrl());
    personMapper.deleteByPrimaryKey(id);
  }

  private void deleteFile(String filePath) {
    String deleteUrl = centerFileServer + "/delete?token=%s&file=%s";
    String token = request.getHeader("x-token");
    HttpClientUtils.get(String.format(deleteUrl, token, filePath));
  }
}
